package com.netsdk.demo.customize;

import static com.netsdk.lib.Utils.getOsPrefix;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;

import com.netsdk.demo.util.CaseMenu;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.NetSDKLib.LLong;
import com.netsdk.lib.ToolKits;
import com.netsdk.lib.callback.impl.DefaultDisconnectCallback;
import com.netsdk.lib.callback.impl.DefaultHaveReconnectCallBack;
import com.netsdk.lib.enumeration.EM_NET_QUERY_TYPE;
import com.netsdk.lib.structure.*;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;

/**
 * ERR230613192
 */
public class QueryServiceLogDemo {
	// SDk对象初始化
	public static final NetSDKLib netsdk = NetSDKLib.NETSDK_INSTANCE;
	public static final NetSDKLib configsdk = NetSDKLib.CONFIG_INSTANCE;

	// 判断是否初始化
	private static boolean bInit = false;
	// 判断log是否打开
	private static boolean bLogOpen = false;
	// 设备信息
	private NetSDKLib.NET_DEVICEINFO_Ex deviceInfo = new NetSDKLib.NET_DEVICEINFO_Ex();
	// 登录句柄
	private NetSDKLib.LLong m_hLoginHandle = new NetSDKLib.LLong(0);

	// 回调函数需要是静态的，防止被系统回收
	// 断线回调
	private static NetSDKLib.fDisConnect disConnectCB = DefaultDisconnectCallback.getINSTANCE();
	// 重连回调
	private static NetSDKLib.fHaveReConnect haveReConnectCB = DefaultHaveReconnectCallBack.getINSTANCE();

	// 编码格式
	public static String encode;

	static {
		String osPrefix = getOsPrefix();
		if (osPrefix.toLowerCase().startsWith("win32-amd64")) {
			encode = "GBK";
		} else if (osPrefix.toLowerCase().startsWith("linux-amd64")) {
			encode = "UTF-8";
		}
	}

	/**
	 * 获取当前时间
	 */
	public static String GetDate() {
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return simpleDate.format(new java.util.Date()).replaceAll("[^0-9]", "-");
	}

	/**
	 * 初始化SDK库
	 */
	public static boolean Init() {
		bInit = netsdk.CLIENT_Init(disConnectCB, null);// 进程启动时，初始化一次
		if (!bInit) {
			System.out.println("Initialize SDK failed");
			return false;
		}
		// 配置日志
		QueryServiceLogDemo.enableLog();

		// 设置断线重连回调接口, 此操作为可选操作，但建议用户进行设置
		netsdk.CLIENT_SetAutoReconnect(haveReConnectCB, null);

		// 设置登录超时时间和尝试次数，可选
		// 登录请求响应超时时间设置为3S
		int waitTime = 3000;
		// 登录时尝试建立链接 1 次
		int tryTimes = 1;
		netsdk.CLIENT_SetConnectTime(waitTime, tryTimes);
		// 设置更多网络参数， NET_PARAM 的nWaittime ， nConnectTryNum 成员与 CLIENT_SetConnectTime
		// 接口设置的登录设备超时时间和尝试次数意义相同,可选
		NetSDKLib.NET_PARAM netParam = new NetSDKLib.NET_PARAM();
		// 登录时尝试建立链接的超时时间
		netParam.nConnectTime = 10000;
		// 设置子连接的超时时间
		netParam.nGetConnInfoTime = 3000;
		netsdk.CLIENT_SetNetworkParam(netParam);
		return true;
	}

	/**
	 * 打开 sdk log
	 */
	private static void enableLog() {
		NetSDKLib.LOG_SET_PRINT_INFO setLog = new NetSDKLib.LOG_SET_PRINT_INFO();
		File path = new File("sdklog/");
		if (!path.exists())
			path.mkdir();

		// 这里的log保存地址依据实际情况自己调整
		String logPath = path.getAbsoluteFile().getParent() + "\\sdklog\\" + "sdklog" + GetDate() + ".log";
		setLog.nPrintStrategy = 0;
		setLog.bSetFilePath = 1;
		System.arraycopy(logPath.getBytes(), 0, setLog.szLogFilePath, 0, logPath.getBytes().length);
		System.out.println(logPath);
		setLog.bSetPrintStrategy = 1;
		bLogOpen = netsdk.CLIENT_LogOpen(setLog);
		if (!bLogOpen)
			System.err.println("Failed to open NetSDK log");
	}

	/**
	 * 高安全登录
	 */
	public void loginWithHighLevel() {
		// 输入结构体参数
		NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstlnParam = new NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY() {
			{
				szIP = m_strIpAddr.getBytes();
				nPort = m_nPort;
				szUserName = m_strUser.getBytes();
				szPassword = m_strPassword.getBytes();
			}
		};
		// 输出结构体参数
		NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam = new NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY();

		// 写入sdk
		m_hLoginHandle = netsdk.CLIENT_LoginWithHighLevelSecurity(pstlnParam, pstOutParam);
		if (m_hLoginHandle.longValue() == 0) {
			System.err.printf("Login Device[%s] Port[%d]Failed. %s\n", m_strIpAddr, m_nPort,
					netsdk.CLIENT_GetLastError());
		} else {
			deviceInfo = pstOutParam.stuDeviceInfo; // 获取设备信息
			System.out.println("Login Success");
			System.out.println("Device Address：" + m_strIpAddr);
			System.out.println("设备包含：" + deviceInfo.byChanNum + "个通道");
		}
	}

	/**
	 * 退出
	 */
	public void logOut() {
		if (m_hLoginHandle.longValue() != 0) {
			netsdk.CLIENT_Logout(m_hLoginHandle);
			System.out.println("LogOut Success");
		}
	}

	/**
	 * 清理sdk环境并退出
	 */
	public static void cleanAndExit() {
		if (bLogOpen) {
			netsdk.CLIENT_LogClose(); // 关闭sdk日志打印
		}
		netsdk.CLIENT_Cleanup(); // 进程关闭时，调用一次
		System.exit(0);
	}

	/**
	 * 查询设备日志条数
	 */
	public int queryDevLogCount() {
		NET_IN_GETCOUNT_LOG_PARAM stIn = new NET_IN_GETCOUNT_LOG_PARAM();
		NET_OUT_GETCOUNT_LOG_PARAM stOut = new NET_OUT_GETCOUNT_LOG_PARAM();
		stIn.stuQueryCondition.stuStartTime = new NET_TIME("2023/1/6/0/0/0");
		// 要查询的结束时间段
		stIn.stuQueryCondition.stuEndTime = new NET_TIME("2023/6/6/20/0/0");

		stIn.stuQueryCondition.emLogType = 0;
		stIn.stuQueryCondition.nLogStuType = 1;
		stIn.stuQueryCondition.nChannelID = 0;
		stIn.stuQueryCondition.nStartNum = 0;
		stIn.stuQueryCondition.nEndNum = 1024;
		stIn.write();
		stOut.write();
		boolean bRet = netsdk.CLIENT_QueryDevLogCount(m_hLoginHandle, stIn.getPointer(), stOut.getPointer(), 5000);
		stIn.read();
		stOut.read();
		if (bRet) {
			System.out.println("QueryDevLogCount Succeed!");
			System.out.println("日志数量：" + stOut.nLogCount);
			return stOut.nLogCount;
		} else {
			System.err.println("QueryDevLogCount Failed!" + ToolKits.getErrorCode());
			return -1;
		}
	}

	/**
	 * 查询设备日志信息
	 */
	public void queryDeviceLog() {
		NET_IN_START_QUERYLOG stIn = new NET_IN_START_QUERYLOG();
		// 查询日志类型
		stIn.emLogType = 0;
		// 查询的时间段
		stIn.stuStartTime = new NET_TIME("2023/1/6/0/0/0");
		stIn.stuEndTime = new NET_TIME("2023/6/6/20/0/0");
		// 按时间升序
		stIn.emResultOrder = 1;
		stIn.write();
		NET_OUT_START_QUERYLOG stOut = new NET_OUT_START_QUERYLOG();
		stOut.write();

		LLong lLogID = netsdk.CLIENT_StartQueryLog(m_hLoginHandle, stIn.getPointer(), stOut.getPointer(), 5000);
		stIn.read();
		stOut.read();
		if (lLogID.longValue() == 0) {
			System.err.println("CLIENT_StartQueryLog Failed!" + ToolKits.getErrorCode());
			return;
		}

		int num = 1024;//某段时间内，日志数量太多,分批查询不建议取太大值出现内存问题
		// 初始化
		NET_LOG_INFO[] info = new NET_LOG_INFO[num];
		for (int i = 0; i < info.length; i++) {
			info[i] = new NET_LOG_INFO();
		}

		NET_IN_QUERYNEXTLOG stIn1 = new NET_IN_QUERYNEXTLOG();
		// 需要查询的日志条数
		stIn1.nGetCount = num;
		stIn1.write();

		NET_OUT_QUERYNEXTLOG stOut1 = new NET_OUT_QUERYNEXTLOG();
		stOut1.nMaxCount = num;
		stOut1.pstuLogInfo = new Memory(info[0].dwSize * num);
		stOut1.pstuLogInfo.clear(info[0].dwSize * num);
		// 将 native 数据初始化
		ToolKits.SetStructArrToPointerData(info, stOut1.pstuLogInfo);
		stOut1.write();
		boolean flg1 = netsdk.CLIENT_QueryNextLog(lLogID, stIn1.getPointer(), stOut1.getPointer(), 5000);
		stIn1.read();
		stOut1.read();
		if (!flg1) {
			System.err.println("CLIENT_QueryNextLog Failed!" + ToolKits.getErrorCode());
			return;
		}
		// 实际返回日志条数
		int nRetCount = stOut1.nRetCount;
		System.out.println("实际返回日志条数: " + nRetCount);
		// 将 native 数据转为 java 数据
		ToolKits.GetPointerDataToStructArr(stOut1.pstuLogInfo, info);
		try {
			for (int i = 0; i < nRetCount; i++) {
				NET_LOG_INFO log = info[i];
				System.out.println("时间: " + log.stuTime.toStringTime()); //某段时间内，日志数量太多,分批查询时，获取批次中日志最大的时间，作为下次的开始时间
				System.out.println("操作者: " + new String(log.szUserName, encode));
				System.out.println("类型: " + new String(log.szLogType, encode));
				System.out.println("日志信息: " + new String(log.stuLogMsg.szLogMessage, encode));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.out.println("实际返回日志条数: " + nRetCount);
		// 手动释放内存
		long peer = Pointer.nativeValue(stOut1.pstuLogInfo);
		Native.free(peer);
		Pointer.nativeValue(stOut1.pstuLogInfo, 0);

		boolean flg2 = netsdk.CLIENT_StopQueryLog(lLogID);
		if (!flg2) {
			System.err.println("CLIENT_StopQueryLog Failed!" + ToolKits.getErrorCode());
			return;
		}
	}

	/**
	 * 获取网卡信息--获取协议栈统计数据
	 */
	public void queryNetDataStat() {


		/**
		 获取协议栈统计数据,(输入结构体NET_IN_NETAPP_NET_DATA_STAT,输出结构体NET_OUT_NETAPP_NET_DATA_STAT)
		 */

		int value = EM_NET_QUERY_TYPE.NET_APP_DATA_STAT.getValue();

		NET_IN_NETAPP_NET_DATA_STAT  input=new NET_IN_NETAPP_NET_DATA_STAT();

		byte[] szEthName = input.szEthName;

		String name="eth0";

		StringToByteArr(name,szEthName,encode);

		Pointer inputPointer=new Memory(input.dwSize);

		inputPointer.clear(input.dwSize);

		ToolKits.SetStructDataToPointer(input,inputPointer,0);

		NET_OUT_NETAPP_NET_DATA_STAT outPut=new NET_OUT_NETAPP_NET_DATA_STAT();

		Pointer outPutPointer=new Memory(outPut.dwSize);

		outPutPointer.clear(outPut.dwSize);

		ToolKits.SetStructDataToPointer(outPut,outPutPointer,0);


		boolean bRet = netsdk.CLIENT_QueryNetStat(m_hLoginHandle,value, inputPointer, input.dwSize,outPutPointer,outPut.dwSize, null,5000);

		if(bRet){
			System.out.println("CLIENT_QueryNetStat  NET_APP_DATA_STAT success!");

			ToolKits.GetPointerData(outPutPointer,outPut);
			Native.free(Pointer.nativeValue(inputPointer)); //清理内存
			Pointer.nativeValue(inputPointer, 0);  //防止重复回收

			Native.free(Pointer.nativeValue(outPutPointer));
			Pointer.nativeValue(outPutPointer, 0);

			/**
			 网卡速度,单位Mbps
			 */
			int nSpeed
					= outPut.nSpeed;
			System.out.println("网卡速度,单位Mbps："+nSpeed);

			/**
			 接收相关统计数据,意义与ifconfig同
			 */
			NET_NETAPP_RECEIVE_STAT stuReceiveStat
					= outPut.stuReceiveStat;
			System.out.println("下行流量速度（K）："+stuReceiveStat.dwSpeed);

			NET_NETAPP_TRANSMIT_STAT stuTransmitStat
					= outPut.stuTransmitStat;
			System.out.println("上行流量速度(K)："+stuTransmitStat.dwSpeed);

		}else {
			System.err.println("CLIENT_StopQueryLog Failed!" + ToolKits.getErrorCode());

		}

	}


	/**
	 * 获取网卡信息--获取物理链路状态
	 */
	public void queryNetLinkStat() {


		/**
		 获取物理链路状态,(输入结构体NET_IN_NETAPP_LINK_STATUS,输出结构体NET_OUT_NETAPP_LINK_STATUS)
		 */

		int value = EM_NET_QUERY_TYPE.NET_APP_LINK_STAT.getValue();

		NET_IN_NETAPP_LINK_STATUS  input=new NET_IN_NETAPP_LINK_STATUS();

		byte[] szEthName = input.szEthName;

		String name="eth0";

		StringToByteArr(name,szEthName,encode);

		Pointer inputPointer=new Memory(input.dwSize);

		inputPointer.clear(input.dwSize);

		ToolKits.SetStructDataToPointer(input,inputPointer,0);

		NET_OUT_NETAPP_LINK_STATUS outPut=new NET_OUT_NETAPP_LINK_STATUS();

		Pointer outPutPointer=new Memory(outPut.dwSize);

		outPutPointer.clear(outPut.dwSize);

		ToolKits.SetStructDataToPointer(outPut,outPutPointer,0);


		boolean bRet = netsdk.CLIENT_QueryNetStat(m_hLoginHandle,value, inputPointer, input.dwSize,outPutPointer,outPut.dwSize, null,5000);

		if(bRet){
			System.out.println("CLIENT_QueryNetStat NET_APP_LINK_STAT success!");

			ToolKits.GetPointerData(outPutPointer,outPut);

			Native.free(Pointer.nativeValue(inputPointer)); //清理内存
			Pointer.nativeValue(inputPointer, 0);  //防止重复回收

			Native.free(Pointer.nativeValue(outPutPointer));
			Pointer.nativeValue(outPutPointer, 0);

			/**
			 是否正在工作
			 */
			int bWorking
					= outPut.bWorking;
			System.out.println("是否正在工作："+bWorking);

			/**
			 IP是否冲突
			 */
			int bIPConflict
					= outPut.bIPConflict;
			System.out.println("IP是否冲突："+bIPConflict);

		}else {
			System.err.println("CLIENT_StopQueryLog Failed!" + ToolKits.getErrorCode());

		}
	}
	public static void StringToByteArr(String src, byte[] dst,String encode) {
		try {
			byte[] GBKBytes = src.getBytes(encode);
			for (int i = 0; i < GBKBytes.length; i++) {
				dst[i] = GBKBytes[i];
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	/******************************** 测试控制台 ***************************************/

	// 配置登陆地址，端口，用户名，密码
	private String m_strIpAddr = "172.12.9.235";// 172.11.1.111 172.11.222.228
	private int m_nPort = 37777;
	private String m_strUser = "admin";
	private String m_strPassword = "admin9235";

	public static void main(String[] args) {
		QueryServiceLogDemo demo = new QueryServiceLogDemo();
		demo.InitTest();
		demo.RunTest();
		demo.EndTest();

	}

	/**
	 * 初始化测试
	 */
	public void InitTest() {
		QueryServiceLogDemo.Init();
		this.loginWithHighLevel();
	}

	/**
	 * 加载测试内容
	 */
	public void RunTest() {
		CaseMenu menu = new CaseMenu();
		menu.addItem(new CaseMenu.Item(this, "查询设备日志条数", "queryDevLogCount"));
		menu.addItem(new CaseMenu.Item(this, "查询设备日志信息", "queryDeviceLog"));
		menu.addItem(new CaseMenu.Item(this, "获取协议栈统计数据", "queryNetDataStat"));
		menu.addItem(new CaseMenu.Item(this, "获取物理链路状态", "queryNetLinkStat"));

		menu.run();
	}

	/**
	 * 结束测试
	 */
	public void EndTest() {
		System.out.println("End Test");
		this.logOut(); // 登出设备
		System.out.println("See You...");
		QueryServiceLogDemo.cleanAndExit(); // 清理资源并退出
	}
	/******************************** 结束 ***************************************/

}
